package com.shopping_back.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopping_back.common.Result;
import com.shopping_back.mapper.*;
import com.shopping_back.pojo.entity.*;
import com.shopping_back.service.IComboService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class ComboServiceImpl implements IComboService {
    private final PromotionActivityMapper promotionActivityMapper;

    private final ComboItemMapper comboItemMapper;

    private final SkuMapper skuMapper;

    private final SpuMapper spuMapper;

    private final OrderItemMapper orderItemMapper;

    private final OrderMainMapper orderMainMapper;

    private final ComboMapper comboMapper;

    @Override
    public PromotionActivity getComboActivity(Long activityId) {
        Combo combo = comboMapper.selectOne(new LambdaQueryWrapper<Combo>().eq(Combo::getActivityId, activityId));
        PromotionActivity activity = promotionActivityMapper.selectById(activityId);
        activity.setComboId(combo.getId());
        return activity;
    }

    public Result getComboItems(Long activityId, Integer page, Integer size) {
        Page<Combo> comboPage = new Page<>(page, size);
        LambdaQueryWrapper<Combo> queryWrapper = new LambdaQueryWrapper<>();
        if (activityId != null) {
            queryWrapper.eq(Combo::getActivityId, activityId);
        }
        comboMapper.selectPage(comboPage, queryWrapper);
        for (Combo combo : comboPage.getRecords()) {
            LambdaQueryWrapper<ComboItem> itemQuery = new LambdaQueryWrapper<>();
            itemQuery.eq(ComboItem::getComboId, combo.getId());
            List<ComboItem> items = comboItemMapper.selectList(itemQuery);
            BigDecimal originalPrice = BigDecimal.ZERO;
            for (ComboItem item : items) {
                Sku sku = skuMapper.selectById(item.getSkuId());
                if (sku != null) {

                    item.setSkuImage(sku.getSkuImage());
                    item.setSkuPrice(sku.getPrice());
                    Spu spu = spuMapper.selectById(sku.getSpuId());
                    if (spu != null) {
                        item.setSkuName(spu.getTitle());
                        item.setSpuMainImage(spu.getMainImage());
                    }
                    originalPrice = originalPrice.add(sku.getPrice().multiply(new BigDecimal(item.getQuantity())));
                } else {
                    item.setSkuName("未知商品");
                    item.setSpuMainImage("");
                    item.setSkuImage("");
                }
            }
            combo.setItems(items);
            combo.setOriginalPrice(originalPrice);
        }
        return Result.success(comboPage);
    }

    @Transactional(rollbackFor = Exception.class)
    public Result placeComboOrder(Long userId, Long activityId, Long comboId) {
        // 检查活动状态
        PromotionActivity activity = promotionActivityMapper.selectById(activityId);
        if (activity == null || !activity.getType().equals(4) || activity.getStatus() != 1 ||
                LocalDateTime.now().isBefore(activity.getStartTime()) || LocalDateTime.now().isAfter(activity.getEndTime())) {
            return Result.error("套餐活动不可用或已结束");
        }

        // 检查套餐
        Combo combo = comboMapper.selectById(comboId);
        if (combo == null || !combo.getActivityId().equals(activityId)) {
            return Result.error("套餐不存在");
        }

        // 获取套餐商品
        LambdaQueryWrapper<ComboItem> itemQuery = new LambdaQueryWrapper<>();
        itemQuery.eq(ComboItem::getComboId, comboId);
        List<ComboItem> items = comboItemMapper.selectList(itemQuery);
        if (items.isEmpty()) {
            return Result.error("套餐商品不存在");
        }

        // 计算原价
        BigDecimal originalPrice = BigDecimal.ZERO;
        for (ComboItem item : items) {
            Sku sku = skuMapper.selectById(item.getSkuId());
            if (sku == null) {
                return Result.error("商品不存在: " + item.getSkuId());
            }
            originalPrice = originalPrice.add(sku.getPrice().multiply(new BigDecimal(item.getQuantity())));
        }

        // 创建订单
        OrderMain order = new OrderMain();
        order.setOrderSn(UUID.randomUUID().toString().replace("-", ""));
        order.setUserId(userId);
        order.setTotalAmount(originalPrice);
        order.setPayAmount(combo.getComboPrice());
        order.setPromotionAmount(originalPrice.subtract(combo.getComboPrice()));
        order.setStatus(0);
        order.setMerchantId(0L); // 假设统一商家
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        orderMainMapper.insert(order);

        for (ComboItem item : items) {
            Sku sku = skuMapper.selectById(item.getSkuId());
            Spu spu = spuMapper.selectById(sku.getSpuId());
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setSkuId(item.getSkuId());
            orderItem.setSkuName(spu.getTitle());
            orderItem.setSkuPrice(sku.getPrice());
            orderItem.setQuantity(item.getQuantity());
            orderItem.setActivityId(activityId);
            orderItem.setSubTotal(sku.getPrice().multiply(new BigDecimal(item.getQuantity())));
            orderItem.setCreateTime(LocalDateTime.now());
            orderItemMapper.insert(orderItem);
        }

        return Result.success(order, "下单成功");
    }
}
